package com.qidian.blog.service.impl;

import com.qidian.blog.factory.MapperFactory;
import com.qidian.blog.mapper.BlogConfigMapper;
import com.qidian.blog.pojo.BlogConfig;
import com.qidian.blog.service.ImageService;
import com.qidian.blog.util.pojo.LayuiTableDTO;
import com.qidian.blog.util.pojo.QDResult;
import org.apache.ibatis.javassist.NotFoundException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 郭浩
 * @Date 2022/10/11 15:05
 */
public class ImageServiceImpl implements ImageService {
    private BlogConfigMapper configMapper = MapperFactory.getMapper(BlogConfigMapper.class);
    public LayuiTableDTO<Map<String,String>> queryByPage(int page, int limit) {
        LayuiTableDTO<Map<String,String>> dto = new LayuiTableDTO<>();
        // 读取配置信息
        BlogConfig config = configMapper.query();
        String dir = config.getImagePath();
        // 读取所有的文件
        File file = new File(dir);
        if(!file.exists() || !file.isDirectory()){
            throw new RuntimeException("文件目录不存在:"+dir);
        }
        // 获取所有文件的名字
        String[] fileNames = file.list();
        // 设置总数量
        dto.setCount(fileNames.length);
        // 读取数据
        List<Map<String,String>> urls = new ArrayList<>();
        int start = (page - 1) * limit;
        for (int x = start;x < start+limit && x < fileNames.length;x ++){
            String url = config.getImageServerUrl()+fileNames[x];
            Map map = new HashMap();
            map.put("url",url);
            urls.add(map);
        }
        dto.setData(urls);
        return dto;
    }

    @Override
    public QDResult delete(String fileName) {
        BlogConfig config = configMapper.query();
        String dir = config.getImagePath();
        File file = new File(dir,fileName);
        if(file.exists() || file.isFile()){
            file.delete();
        }
        return QDResult.ok();
    }
}
